package com.cbgolf.oa.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.OrderAdapter;
import com.cbgolf.oa.contract.IOrderContract.IOrderFragPresenter;
import com.cbgolf.oa.contract.IOrderContract.IOrderFragView;
import com.cbgolf.oa.event.EventOrder;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.presenter.OrderFragPresenterImp;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.viewbean.OrderBean;
import com.cbgolf.oa.views.ErrorView;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author lq
 * @date 2017/6/30
 */

public class OrderFragment extends Fragment implements OnRefreshLoadmoreListener, IOrderFragView {

    private View contentView;
    @BindView(R.id.f_order_listview)
    ListView listView;
    @BindView(R.id.refresh)
    SmartRefreshLayout refreshLayout;

    private ErrorView errorView;

    private OrderAdapter adapter;
    private List<OrderBean> listData = new ArrayList<>();
    /**
     * 订单状态
     */
    private static final String ORDER_STATE = "orderState";
    private String orderState;
    /**
     * 订单类型
     */
    private static final String ORDER_TYPE = "orderType";
    private String orderType;

    /**
     * presenter
     */
    private IOrderFragPresenter presenter;

    public static OrderFragment newInstance(String ordetState, String orderType) {
        OrderFragment f_order = new OrderFragment();
        Bundle b = new Bundle();
        b.putString(ORDER_STATE, ordetState);
        b.putString(ORDER_TYPE, orderType);
        f_order.setArguments(b);
        return f_order;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderState = DataUtil.getBundleString(getArguments(), ORDER_STATE);
        orderType = DataUtil.getBundleString(getArguments(), ORDER_TYPE);
        contentView = getActivity().getLayoutInflater().inflate(R.layout.f_order, null);
        init();
        AutoUtil.autoSize(contentView);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (null == contentView) {
            contentView = inflater.inflate(R.layout.f_order, null);
            init();
            AutoUtil.autoSize(contentView);
        }
        return contentView;
    }

    private void init() {
        findViews();
        setViews();
        setListener();
    }

    @Override
    public void onResume() {
        super.onResume();
//        OrderManager.isOrderStateAll(orderState)
//                && OrderManager.isOrderTypeAll(orderType)
//                &&
        if (isVisible) {
            loadData();
        }
    }

    private void findViews() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        ButterKnife.bind(this, contentView);
        errorView = new ErrorView(getActivity(), contentView);
        presenter = new OrderFragPresenterImp(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        stopProgress();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setViews() {
        adapter = new OrderAdapter(getActivity());
        listView.setAdapter(adapter);
        ViewUtils.setRefreshDeliveryHeader(getActivity(), refreshLayout);
    }

    private void setListener() {
        refreshLayout.setOnRefreshLoadmoreListener(this);
    }

    @Override
    public void setPresenter(EventOrder presenter) {

    }

    @Override
    public void getDataFail(String msg, int code) {
        if (null != errorView) {
            errorView.setBackgroundColor(getActivity(), R.color.bg);
            errorView.showError(refreshLayout, msg, code, () -> loadData());
        }
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDataOver(EventOrder event) {
        stopProgress();
        if (null == event || event.target != DataManager.ORDER_LIST) {
            return;
        }
        if (!Util.isEquals(event.orderState, orderState)
                || !Util.isEquals(event.orderType, orderType)) {
            return;
        }
        switch (event.requestType) {
            case DataUtil.INITDATA:
                if (Util.listIsNull(event.listOrder)) {
                    getDataFail(event.errorMsg, event.errorCode);
                    return;
                }
                setData(event.listOrder);
                break;
            case DataUtil.REFRESH:
                if (Util.listIsNull(event.listOrder)) {
                    return;
                }
                setData(event.listOrder);
                break;
            case DataUtil.LOADMORE:
                if (Util.listIsNull(event.listOrder)) {
                    return;
                }
                adapter.addData(event.listOrder);
                adapter.upDateUI();
                break;
            default:
                break;
        }

    }

    private void setData(List<OrderBean> list) {
        if (null != errorView) {
            errorView.showData(refreshLayout);
        }
        listData.clear();
        listData.addAll(list);
        adapter.setList(listData);
        adapter.upDateUI();
    }

    @Override
    public void showProgress() {
        AnimaUtil.showLoading(getActivity(), errorView.getLoadingTv());
    }

    @Override
    public void stopProgress() {
        if (null != refreshLayout) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadmore();
        }
        AnimaUtil.stopLoading();
    }

    private void loadData() {
        if (null != presenter) {
            presenter.getData(orderState, orderType, DataUtil.INITDATA, isVisible);
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        if (null != presenter) {
            presenter.getData(orderState, orderType, DataUtil.LOADMORE, isVisible);
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        if (null != presenter) {
            presenter.getData(orderState, orderType, DataUtil.REFRESH, isVisible);
        }
    }

    public void refreshData() {
        loadData();
    }

    private boolean isVisible;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
    }

}
